<template>
	<view class="container padding-lr-sm">
    
    <view class="flex justify-between header-titlesc">
      <text class="textStyles">送餐信息</text>
      <text class="clearClass" @click="clearAdded">清空</text>
    </view>
		<view class="botSec margin-top-sm">
			<view class="bslis padding-lr-sm">
				<view class="rowItem flex align-center">
					<text class="tit text-c6">送餐地址</text>
					<view class="inBox flex-sub flex align-center"  @click="chooseLocation">
						<!-- #ifdef MP-WEIXIN -->
						<picker mode="region" @change="regionChange" :value="region" class="input flex-sub text-lg textoverflow" style="padding-right: 20rpx;" :disabled="true">
							{{ addressData.address }}
							<view v-if="!addressData.address||addressData.address==' '" class="pac_df">点击选择</view>
						</picker>
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<!-- <view class="flex-sub flex padding-tb-xs" @click="chooseLocation">
							<input class="input flex-sub disabled text-lg" type="text" disabled v-model="addressData.address" placeholder="请输入定位您的送餐省市县" placeholder-class="plhcolor" />
						</view> -->
						<!-- #endif -->
						<view class="text-them padding text-ngreen">
							<text class="cuIcon-locationfill fcon-a-dingwei5"></text>
							<text>定位</text>
						</view>
					</view>
				</view>
				<view class="rowItem b_b flex align-center text-lg">
					<text class="tit text-c6">门牌号</text>
					<input class="input flex-sub" type="text" v-model="addressData.vaddre_detail" placeholder="楼号、门牌" placeholder-class="plhcolor"/>
				</view>
				<view class="rowItem b_b flex align-center text-lg">
					<text class="tit text-c6">联系人</text>
					<input class="input flex-sub" type="text" v-model="addressData.vname" placeholder-class="plhcolor" placeholder="请输入联系人" />
				</view>
				<view class="rowItem b_b flex align-center text-lg">
					<text class="tit text-c6">手机号</text>
					<input class="input flex-sub" type="number" v-model="addressData.vphone" placeholder="请输入您的手机号" placeholder-class="plhcolor" />
				</view>
				<view class="rowItem b_b flex align-center">
					<text class="tit text-c6">标&nbsp;&nbsp;&nbsp;签</text>
					<view v-for="(item,index) in tipList" :key="index" :class="{act:tipId==item.id}" @click="selecBtn(item)" class="rbitm margin-right-sm text-center text-c9 padding-lr-sm">
						{{item.name}}
					</view>
				</view>
				<!-- <view class="rowItem flex align-center margin-top-sm">
					<view class="flex-sub flex align-center padding-tb-sm">
						<text class="margin-right-xs text-xl" :class="isDef?'text-ngreen cuIcon-roundcheckfill':'cuIcon-round text-c9'"></text>
						设为默认地址
					</view>
					<view class="clearBtn text-c6 padding" >
						清空
					</view>
				</view> -->
			</view>
		</view>
		<view class="full_btn fixed padding-top-sm"><view class="mbtn" @click="tapSaveAddress" >保存</view></view>
	</view>
</template>

<script lang="ts"  type="module" setup>
  //getsaveAddressList
	import { ref,onMounted } from "vue";
  import { onShow,onLoad } from '@dcloudio/uni-app';
  import mFormRule from "@/config/formRule";
  import mChecker from "@/utils/checker";
  import { showLoading, hideLoading,mnavTo } from '@/utils/helper';
  import { getsaveAddressList,identifyAddressData,getAddressList } from '@/api/vmeitime-http/index.js'
  // import AddressParse from './tb-address-parse.min.js';
  import mApi from "@/utils/mapi";
  import global from '@/utils/global';
   import QQMapWX from './qqmap-wx-jssdk.min.js';
   import { useUserStore } from '@/stores/commonStore';
   const userStore = useUserStore();
  // const QQMapWX = require('./qqmap-wx-jssdk.js')
	const isFrEdit = ref(false);
	const region = ref(['湖南省','长沙市']);
  const isLogin = ref(false)  //是否登录
	// 地址
	const addressData= ref({  //地址列表
		vname: '',  //联系人
		vphone: '', //电话
		address: '', //3-3原-在地图选择省市区
		labelname: '', //签名
		vaddre_detail:'', //门牌
    sourceType:'',
    vcountyCode:'', //省市区编码
		city:'',
		area:'',
    vdefault:'6',
    vprovince:'', //省
    vcity:'',  //市
    vcounty:'',//区
    naddress_id:'' ,//
    latitude:0,
    longitude:0,
    addre_type:'' //标签  1136 家 1137  公司  1138学校
		// vdefault: '6' //5默认，6非默认
	})
	const isDef = ref(false)
	const tipId = ref('-1')//标签id
  const filterCode = ref(['441900','442000','460400','620200'])//过滤指定国家地标局同步编号(修改请先联系：tks)
	const tipList = ref([
		{
			id:'0',
			name:'家'
		},
		{
			id:'1',
			name:'公司'
		},
		{
			id:'2',
			name:'学校'
		},
	])
  //逆解析城市信息
  const detailAddress= ref<any>()
  //快速识别
  const distinguish = async (textName:any)=> {
    try{
       showLoading()
       console.log('解析地址请求参数------------------------------------------------------------',textName)
       let res = await identifyAddressData({
         address:textName
       })
       if(res.result){
         hideLoading();
         addressData.value.vcountyCode = res.object.countyId
       }
       console.log('解析地址返回参数------------------------------------------------------------',res)
     }catch (e) {
      hideLoading();
      mApi.msg('网络繁忙，请稍后再试!');
    }
  }
  onShow(()=>{
    // isLogin.value = uni.getStorageSync(global.IS_LOGIN) || false;
    // console.log('是否登录--------------------------------------------------',isLogin.value )
    // if(!isLogin.value){
    //   if (!global.CENTER_LOGIN_PAGE) {
    //   	global.CENTER_LOGIN_PAGE = true; //进入登录页面
    //      mnavTo(`/pages/login/login`)
    //   }
    // }
  })
  onLoad((option)=>{
    let title = '新增收货地址';
    if(option.flagStatue){
      title = '编辑收货地址';
      isFrEdit.value = true;
      addressData.value = JSON.parse(option.data);
      // addressData.value = JSON.parse(uni.getStorageSync('userInfos')).curSelecAdress
      let vprovinceName  = addressData.value.vprovince || ''
      let vcityName = addressData.value.vcity || ''
      let vcountyParaName =  addressData.value.vcounty
      let countyParams = filterCode.value.includes(addressData.value.vcounty) ? '' : addressData.value.vcounty;
     
      // console.log('tipId.value-----------------------------------------',tipId.value)
      addressData.value.address = addressData.value.vprovince + ' ' + addressData.value.vcity + (countyParams?' ' +countyParams:'');
      region.value.splice(0,1,vprovinceName);
      region.value.splice(1,1,vcityName);
      region.value.splice(2,1,vcountyParaName);
      // console.log('addressData.value--------------------------',addressData.value.address)
      addressData.value.sourceType = 'EDIT';
      isDef.value = addressData.value.vdefault == '5' ? true : false
      // console.log('opitons_addressData_params1:',addressData.value);
     const addreTypeMap = {
         '1136': '0',
         '1137': '1',
         '1138': '2'
     };
     tipId.value = addreTypeMap[addressData.value.addre_type] || '';
      console.log('addressData.value.addre_type---------------------',addressData.value.addre_type)
    }
    uni.setNavigationBarTitle({title: title});
  })

  const btnisDef = () => {
    isDef.value=!isDef.value
    isDef.value ? addressData.value.vdefault = '5' : addressData.value.vdefault = '6'
    console.log('----------------------',addressData.value.vdefault)
  }
	//选择地址
	const regionChange = e=>{
		region.value = e.detail.value;
		addressData.value.sourceType = 'CHOICE';
		addressData.value.vcountyCode = e.detail.code[2]||'';
		// currentCityName.value = region.value[1]||'';
		addressData.value.address = (region.value[0]||'') + ' ' + (region.value[1]||'') + (region.value[2]?(' ' + region.value[2]):'');
    
    console.log('选择eee++++++++++++++++++++++++++++++++++++++++++++++++++',e)
    console.log('选择region',region.value)
	};
	// 定位
	//地图选择地址
	const chooseLocation = ()=> {
		wx.chooseLocation({
			success: data => {
				console.log('data', data);
				// address: "湖南省长沙市芙蓉区嘉雨路189号"
				// errMsg: "chooseLocation:ok"
				// latitude: 28.20279
				// longitude: 113.03539
				// name: "春和景明酒店(嘉雨路)"
				// that.addressData.vaddre_detail = data.name;//省市区取不到          EM7BZ-OVYRX-WPY46-7JV45-HFFB3-TDBMV				
        if(data.address){
          console.log('快速识别接口快速识别接口快速识别接口快速识别接口快速识别接口data.address-----------------------------',data.address)
          addressData.value.latitude = data.latitude
          addressData.value.longitude = data.longitude
          let detAdres = (data.address||'') + (data.name||'')
          const addressParts = detAdres.split(/(?<=区|市|省)/); // 使用正则表达式确保区、市、省不丢失
          const province = addressParts[0];  //省
          const city = addressParts[1]; //市
          const district = addressParts[2]; //区
          // const detailAddress = addressParts.slice(3).join(''); // 获取详细地址，
          detailAddress.value = data.address
          // console.log('地图------------------------------------------------------',detAdres, province,city,district,detailAddress)
          addressData.value.address = province + ' ' + city + ' ' + district
          // addressData.value.vaddre_detail = detailAddress
          addressData.value.vaddre_detail = data.name
          region.value.splice(0,1,province);
          region.value.splice(1,1,city);
          region.value.splice(2,1,district);
          if (!province.includes('省') && !province.includes('市')) {
              console.log('这里没有获取到省市', province);
              maphq(data.latitude, data.longitude);
              return
          }   
          distinguish(detailAddress.value)  //快速识别接口
          // distinguish(addressParts)
          // console.log('this.addressData-------------------------------------------',addressData.value.vcountyCode);
        }	
			}
		});
	};
 
  //地址逆解析
  const maphq = (latitude:any,longitude:any) => {
      // console.log('地址逆解析----------------------------------',latitude,longitude)
			var mapsdk = new QQMapWX({
				key: 'DKYBZ-DBURJ-I74F2-X63NG-MTHXK-CUF3L' // 必填
			});
			mapsdk.reverseGeocoder({
				//Object格式
				location: {
					latitude:latitude,
					longitude:longitude
				},
				success: (res:any) => {
            let temp =  res.result.ad_info
            distinguish(temp.province + temp.city + detailAddress.value)
            console.log('城市信息城市信息--------------',res.result.ad_info); //城市信息
				},
				fail: (error:any) => {
          mApi.msg('获取地址失败');
					console.error(error);
				}
			});
		}
	// 清空
	const clearAdded = ()=>{
		addressData.value = {
			vname: '',  //联系人
			vphone: '', //电话
			address: '', //3-3原-在地图选择省市区
			labelname: '', //签名
			vaddre_detail:'', //门牌
			sourceType:'',
			vcountyCode:'', //省市区编码
			city:'',
			area:'',
			vdefault:'',
			vprovince:'', //省
			vcity:'',  //市
			vcounty:'',//区
      latitude:0,
      longitude:0,
			naddress_id:'', //
      addre_type:'' //分类
		}
	};
	// 保存
	// const tapSaveAddress = ()=>{
		
	// }
	// import { onShow } from '@dcloudio/uni-app';
	// onShow(() => {})
	
  // const onblur = (source : string = '') => {
  // 	switch (source) {
  // 		case 'isNameFocused':
  // 			console.log('123')
  // 			inputStatus.value[0] = true
  // 			nameFocus.value = false
  // 			break;
  // 		case 'isCodeFocused':
  // 			inputStatus.value[1] = true
  // 			codeFocus.value = false
  // 			break;
  // 		case 'isPwdFocused':
  // 			inputStatus.value[2] = true
  // 			pwdFocus.value = false
  // 			break;
  // 		default:
  // 			break;
  // 	}
  // }
  
  // const canSubmit = computed(() => {
  // 	let checkParam = mChecker.check(
  // 		addressData.value,
  // 		mFormRule.bindCardRule
  // 	);
  // 	let allfocs = inputStatus.value.some(item=>item==false)
  // 	errText.value = !allfocs?mChecker.error.msg:''
  // 	return checkParam
  // });
  
  const selecBtn = (item:any) => {
    tipId.value = item.id
    switch (item.name) {
        case '学校':
          addressData.value.addre_type = '1138';
          break;
        case '公司':
          addressData.value.addre_type = '1137';
          break;
        default:
          addressData.value.addre_type = '1136';
          break;
    }
    // console.log(addressData.value.labelname)
  }
  
  // 提交表单
  const tapSaveAddress = async (isFlag : any) => {
    // console.log('提交表单提交表单提交表单提交表单提交表单提交表单提交表单')
  	let checkParam = mChecker.check(
  		addressData.value,
  		mFormRule.addAdressRule
  	);
  	// console.log('checkSendCode', checkParam);
  	if (!checkParam) {
  		mApi.msg(mChecker.error.msg);
  		return;
  	}
    if (!addressData.value.longitude || !addressData.value.latitude) {
      mApi.msg('地址经纬度不能为空或无效');
      return;
    }
  	try {
  		showLoading()
      console.log(addressData.value)
      let paramData:any = {
        vphone : addressData.value.vphone,   //手机号码
        // nmember_id:152998,  //
        vcounty:addressData.value.vcountyCode,
        sourceType:addressData.value.sourceType,
        vname:addressData.value.vname,  //联系人
        addre_type:addressData.value.addre_type, //  分类
        vaddre_detail:addressData.value.vaddre_detail, //详细地址
        // address:addressData.value.address,
        vdefault:addressData.value.vdefault,//5
        latitude:addressData.value.latitude,  //经纬度
        longitude:addressData.value.longitude
      }
      if (isFrEdit.value) {
        console.log(addressData.value.naddress_id)
      	paramData.naddress_id = addressData.value.naddress_id
      }
      console.log('提交的地址信息-------------',paramData)
  		let res = await getsaveAddressList(paramData)  
		
      console.log(res)
  		hideLoading()
  		if (res.result) {
			isFrEdit.value&&getAddressListData()
  			mApi.msg('提交成功')
  			uni.navigateBack()
  		} else {
  			mApi.msg(res.shortMessage || '提交失败！')
  		}
  	} catch (e) {
  		hideLoading()
  		console.error(e)
  	}
  }
	//获取地址列表
	const getAddressListData = async () => {
		// console.log('我是获取地址列表的接口')
		showLoading();
		try {
			let res = await getAddressList({channelNo:'1114'})
			hideLoading();
			if (res) {
				let nres = res || [];
				nres.forEach((item : any) => {
					item.vaddre_detail = item.vaddre_detail.replace(/&middot;/g, '·');
					//删除缓存
					let cachId = userStore.curSelecAdress.naddress_id || '';
					item.adrs = (item.vprovince || '') + (item.vcity || '') + (item.vcounty || '') + (item.vaddre_detail || '');
					if (cachId && cachId == item.naddress_id) {
						userStore.setSelectAdress(item);
						userStore.setChangeAdress(true);
					}
				})
			}
		} catch (e) {
			hideLoading();
			// mapi.msg('获取门店失败!');
		}
	}	
		
</script>

<style lang="scss">
  .header-titlesc{
    height: 140rpx;
    border-radius: 10px;
    background: linear-gradient(90deg, #F9F7FF 2.06%, #FFF 97%);
    padding: 40rpx 20rpx 0rpx 20rpx;
    position: relative;
    top: 60rpx;
    z-index: 2;
    .textStyles{
      color: #333;
      font-feature-settings: 'liga' off, 'clig' off;
      font-family: "Microsoft YaHei UI";
      font-size: 32rpx;
      font-style: normal;
      font-weight: 700;
      line-height: 150%; /* 24px */
    }
    .clearClass{
      color: #666;
      font-family: "Microsoft YaHei UI";
      font-size: 28rpx;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
    }
  }
  .textoverflow{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 250rpx;
  }
	.container{
		// padding-top: 100rpx;
		min-height: 100vh;
		background: #F2F3F7;
		padding-bottom: 180rpx;
	}
	.topSec{
		background: #fff;
		border-radius: 20rpx;
		min-height: 296rpx;
		box-shadow: 0px 5px 25rpx 0px rgba(105, 105, 105, 0.07);
		.text-ar{
			width: 100%;
			height: 160rpx;
			margin: 30rpx 0 20rpx 0;
		}
		.idebtn{
			width: 172rpx;
			height: 50rpx;
			line-height: 51rpx;
			border-radius: 50rpx;
			background: $base-color;
		}
		.cu-form-group{
			border-radius: 20rpx 20rpx 0 0;
		}
	}
	
	.noticebox{
		padding: 20rpx 30rpx 10rpx 40rpx;
		position: fixed;
		height: 100rpx;
		width: 100vw;
		left: 0;
		top: 0;
		/* #ifdef H5 */
		top: var(--window-top);
		/* #endif */
		background: #FFF7E8;
		color: #FFB74A;
		line-height: 1.5;
		z-index: 33;
	}
	.botSec{
		// min-height: 650rpx;
    margin-top: 50rpx;
		background: #fff;
		border-radius: 20rpx;
		box-shadow: 0px 5px 25rpx 0px rgba(105, 105, 105, 0.07);
    position: relative;
    z-index: 99;
		.title{
			height: 140rpx;
			border-radius: 20rpx 20rpx 0 0;
			background: linear-gradient(90deg, #F9F7FF 2.06%, #FFF 97%);
		}
		.bslis{
			margin-top: -20rpx;
			min-height: 550rpx;
			border-radius: 20rpx;
			background: #FFF;
			box-shadow: 0px 5px 25rpx 0px rgba(105, 105, 105, 0.07);
		}
	}
	
	.rowItem{
		height: 100rpx;
		border-bottom:1px solid #E6EBF4;
    &:last-child{
     border-bottom:1px solid none !important;
    }
		.tit{
			width: 160rpx;
			font-size: 32rpx;
		}
	}
	.inBox{
		.input {
			line-height: 1.7;
		}
		&.pdl{
			padding:20rpx 0;
		}
		.pac_df{
			font-size: 26rpx;
			color: #CBCBCB;
      width: 300rpx;
		}
    .overflowtext{
      display: block;
      border: 1px solid red;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 200rpx;
    }
	}
	.rbitm{
		min-width: 62rpx;
		height: 48rpx;
		line-height: 48rpx;
		border-radius: 5px;
		border: 1px solid rgba(153, 153, 153, 0.50);
		&.act{
			border: 1px solid rgba(83, 168, 127, 0.50);
			background: #C4E8D1;
			color: $base-color;
		}
		
	}
	.plhcolor{
		font-size: 28rpx;
		color: #CBCBCB;
	}
</style>
